/**
 * File: PropertiesManager.java
 * User: z3y2
 * Date: 2010-12-16
 * Time: 下午01:15:58
 * Copyright: (c) 2010 All Rights Reserved
 */
package com.mypack.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.mypack.exception.CommonException;

/**
 * 属性文件管理器
 * @author z3y2
 */
public final class PropertiesManager {

	/**
	 * 系统配置参数持有者,不可变,在系统启动时就初始化好了
	 */
	private static Properties properties = new Properties();
	
	/**
	 * 系统配置文件路径
	 */
	private static final String CONFIG_FILE_PATH = "config.properties";
	
	/**
	 * 日志记录对象
	 */
	private static Logger logger = Logger.getLogger(PropertiesManager.class.getName());
	
	/**
	 * 每一分钟检查一次配置文件是否改变, 毫秒为单位 , 默认为每分钟刷新一次
	 * GAE 不能启动线程
	 */
	// private static final int READ_FILE_INTERVAL = 1 * 1000; 

	
	static {
		initialize(); // 初始化配置文件
	}
	
	/**
	 * 对配置文件进行初始化
	 */
	public static void initialize() {
		properties.clear();
		InputStream is = null;
		try {
			is = Tool.getInputStream(CONFIG_FILE_PATH);
			properties.load(is);
			
			if (logger.isLoggable(Level.INFO)) {
				logger.info("--------------------------- " + CONFIG_FILE_PATH + " initialized successfully ----------------------------");
				logger.info("config file content --> " + properties.toString());
				
				is = Tool.getInputStream(CONFIG_FILE_PATH);
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				for (String line = reader.readLine(); line != null; line = reader.readLine()) {
					logger.info(line);
				}
				Tool.release(reader);
			}
		} catch (IOException ex) {
			logger.log(Level.WARNING, ex.getMessage(), ex);
			throw new CommonException(ex.getMessage(), ex);
		} finally {
			Tool.release(is);
		}
	}
	
	/**
	 * 查询值, 返回字符串的形式, 如果没有找到值则返回空<null>
	 * @param key 键,对应于配置文件里的键
	 * @return 值 ,对应配置文件里所键对应的值
	 */
	public static String get(String key) {
		Assert.notNull(key);
		return properties.getProperty(key);
	}
	
	/**
	 * 根据传递进来的键查找值,如果找不到则抛出异常
	 * @param key 对应于配置文件里的键
	 * @return 对应配置文件里所键对应的值
	 * @throws CommonException 当不存在时,则抛出此异常
	 */
	public static String getRequired(String key) throws CommonException {
		Assert.notNull(key);
		if (!properties.containsKey(key)) {
			throw new IllegalArgumentException("the key[" + key + "]'s value not exists.");
		}
		return properties.getProperty(key);
	}
	
	/**
	 * 得到一个整数值
	 * @param key
	 * @return 方法会自动自行转型 
	 */
	public static Integer getInt(String key) {
		return Integer.valueOf(getRequired(key));
	}
	
	// ----------------------------------------------------------------------------------- inner watchdog class
	
	
	// ------------------------------------------------------------------------------------- Private Method
	
	private PropertiesManager() {
		
	}
	
}
